//################################## 初始化 ######################################
var layers = [];													// 声明层
var player;															// 用户角色
var scene;															// 用户场景
var camera = new PIXI.Container();									// 创建镜头
//################################ 构造渲染器 #####################################
const app = new PIXI.Application({ background: '#1099bb', resizeTo: window });
app.ticker.add((delta) => 
{ 	
	hotkeys.update();
	if(player) {
		camera.position.set(app.renderer.screen.width/2, app.renderer.screen.height/2);
		camera.pivot.set(Math.floor(player.x), Math.ceil(player.y));
	}
	if(scene) scene.update();
	L2D.UIManager.update();
});
document.body.appendChild(app.view);

window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", function() {
	resize(800, 600);
});

function resize(width, height) {
	const screenRect = app.view.getBoundingClientRect();
	app.renderer.resize(screenRect.width, screenRect.height);
	
	let offsetWidth = 0;
	let offsetHeight = 0;
	if (window.orientation === 90 || window.orientation === -90) {
	  offsetWidth = screenRect.height;
	  offsetHeight = screenRect.width;
	} else {
	  offsetWidth = screenRect.width;
	  offsetHeight = screenRect.height;
	}
	
	const aspectRatio = offsetHeight / offsetWidth;
	
	// fixWidth, orientation="portrait"
	const newWidth = offsetWidth;
	const scale = newWidth / width;
	const newHeight = height * scale;
	
	camera.scale.x = newWidth / width;
	camera.scale.y = newHeight / height;
	
	//if (window.orientation === 180 || window.orientation === -180 ||
	//	window.orientation === 90 || window.orientation === -90) {
	if(false) {
	  camera.rotation = -Math.PI / 2;
	  camera.y = newWidth;
	} else {
	  camera.rotation = 0;
	  camera.y = 0;
	}
	
	camera.realScreen = {
	  realWidth: offsetWidth,
	  realHeight: offsetHeight,
	  width,
	  height,
	  top: 0,
	  bottom: offsetHeight / scale,
	  left: 0,
	  right: width,
	  aspectRatio
	};
	camera.realScreen.width = camera.realScreen.right - camera.realScreen.left;
	camera.realScreen.height = camera.realScreen.bottom - camera.realScreen.top;
}

//################################ 读取启动配置 ####################################
L2D.Loader.load("res/startup.json", null, function(json) {
	player = L2D.Loader.load(json.content.character);				// 新建主角
	player.speed = 1;												// 为主角设定速度
	player.state = `idea`;											// 为主角添加动作
	player.isCylinder = true;										// 主角是一个圆柱体
	player.x = json.content.location.x;								// 为主角设置坐标
	player.y = json.content.location.y;	
	
	scene = L2D.Loader.load(json.content.scene, null, function() {
		scene.fight(player.position, 3000);
	});																// 新建地图
	scene.player = player; 											// 设置地图主角
	
	scene.addChild(player);											// 将角色加入地图中
	camera.addChild(scene);											// 将地图加入层中
	app.stage.addChild(camera);										// 将镜头加入场景中
	
	app.stage.addChild(L2D.UIManager);								// 将UI层加入场景中
	app.stage.addChild(L2D.UserInterface);							// 添加用户接口到场景中
	
	resize(800, 600);
});

//############################### 配置用户输入事件 ##################################
var targetPoint;
camera.eventMode = 'static';
camera.on('pointerdown', (e) => {
	if(L2D.UIManager.children.length > 0)
		return;
	
	targetPoint = { x:(e.x-camera.x)/camera.scale.x+camera.pivot.x, y:(e.y-camera.y)/camera.scale.y+camera.pivot.y };	
	// 检测是否命中NPC
	for(var i = 0; i < scene.children.length; i++) {
		if(scene.children[i].name) {
			const npc = scene.children[i];
			if(targetPoint.x > npc.x - 16 && targetPoint.x < npc.x + 16 &&
			   targetPoint.y > npc.y - 36 && targetPoint.y < npc.y + 8) {
				   // 取消NPC寻路动作
				   if(player.action) player.action.path = null;
				   player.talkTo(npc);
				   return;
			   }
		}
	}
	
	isPressed = true;
	//player.moveTo(targetPoint);
	var loopSetTarget = function() {
		if(isPressed) {
			player.moveTo(targetPoint);
			setTimeout(loopSetTarget, 100);
		}
	}
	//setTimeout(loopSetTarget, 100);
});

const maxSpeed=1.7;
const speedStep=40;

function fixVelocity(x, y) {
	var fixedY = y * player.speed/speedStep;
	player.body.velocity.y += fixedY;
	if(fixedY < 0) {
		if(player.body.velocity.y < -player.speed*maxSpeed)
			player.body.velocity.y = -player.speed*maxSpeed;
	}
	else if(fixedY > 0) {
		if(player.body.velocity.y > player.speed*maxSpeed)
			player.body.velocity.y = player.speed*maxSpeed;
	}
	
	var fixedX = x * player.speed/speedStep;
	player.body.velocity.x += fixedX;
	if(fixedX < 0) {
		if(player.body.velocity.x < -player.speed*maxSpeed)
			player.body.velocity.x = -player.speed*maxSpeed;
	}
	else if(fixedX > 0) {
		if(player.body.velocity.x > player.speed*maxSpeed)
			player.body.velocity.x = player.speed*maxSpeed;
	}
	
	Matter.Body.setVelocity(player.body, player.body.velocity);
}

L2D.Keys("space", (e) => {
	player.attack();
});

L2D.Keys("w", (e) => {
	if(scene.battle) {
		fixVelocity(0, -1);
	}
	else {
		player.moveTo({ x:player.x, y:player.y-1 });
	}
});

L2D.Keys("s", (e) => {
	if(scene.battle) {
		fixVelocity(0, 1);
	} else {
		player.moveTo({ x:player.x, y:player.y+1 });
	}
});

L2D.Keys("a", (e) => {
	if(scene.battle) {
		fixVelocity(-1, 0);
	} else {
		player.moveTo({ x:player.x-1, y:player.y });
	}
});

L2D.Keys("d", (e) => {
	if(scene.battle) { 
		fixVelocity(1, 0);
	} else {
		player.moveTo({ x:player.x + 1, y:player.y });
	}
});

L2D.Keys("w+a", (e) => {
	if(scene.battle) {
		fixVelocity(-1, -1);
	} else {
		player.moveTo({ x:player.x-1, y:player.y-1 });
	}
});

L2D.Keys("w+d", (e) => {
	if(scene.battle) {
		fixVelocity(1, -1);
	} else {
		player.moveTo({ x:player.x+1, y:player.y-1 });
	}
});

L2D.Keys("s+a", (e) => {
	if(scene.battle) {
		fixVelocity(-1, 1);
	} else {
		player.moveTo({ x:player.x-1, y:player.y+1 });
	}
});

L2D.Keys("s+d", (e) => {
	if(scene.battle) {
		fixVelocity(1, 1);
	} else {
		player.moveTo({ x:player.x+1, y:player.y+1 });
	}
});